<template>
  <el-breadcrumb class="app-breadcrumb" separator-class="el-icon-arrow-right">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="item in levelList" :key="item.path">
        <span
          class="no-redirect"
          :style="{
            color:
              layoutTheme === 'dark' ? variables.darkText : variables.lightText
          }"
        >{{ item.meta.title }}</span>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import { mapState } from 'vuex'
import variables from '@/assets/styles/variables.scss'
import pathToRegexp from 'path-to-regexp'
export default {
  data() {
    return {
      levelList: null
    }
  },
  computed: {
    ...mapState({
      layoutTheme: state => state.settings.layoutTheme
    }),
    variables() {
      return variables
    }
  },
  watch: {
    $route(route) {
      // if you go to the redirect page, do not update the breadcrumbs
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      let matched = []
      const first = JSON.stringify(this.$route.matched[0].meta)
      const second = JSON.stringify(this.$route.matched[1].meta)
      if (first === second) {
        // 一级路由为菜单
        matched.push(this.$route.matched[0])
      } else {
        matched = this.$route.matched.filter(
          item => item.meta && item.meta.title
        )
      }
      this.levelList = matched.filter(
        item => item.meta && item.meta.title && item.meta.breadcrumb !== false
      )
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim() === '系统首页' // trim去除首尾空格
    },
    pathCompile(path) {
      const { params } = this.$route
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;
  .no-redirect {
    // color: #97a8be;
    cursor: text;
  }
}
</style>
